import Log from 'Utils/Log';
let errorNum = 0
let ctx
let getImageInfo = (canvas, imgPath, resolve, reject)=>{
    var img=canvas.createImage();
    img.onload=function(){
        resolve(img);
    }
    img.src = imgPath;
}
/**
 * 渲染圆形图片
 *
 * @param {Object} obj
 */
let drawImg = function (obj) {
    ctx.save();
    ctx.beginPath();
    ctx.arc(obj.width / 2 + obj.x, obj.height / 2 + obj.y, obj.width / 2, 0, Math.PI * 2, false);
    ctx.clip();
    ctx.drawImage(obj.img, obj.x, obj.y, obj.width, obj.height);
    ctx.restore();
}

export async function haibaoGet(data){
    errorNum = 0
    return new Promise((cbResolve, cbReject)=> {
        let query;
        if( data._this ){
            query = data._this.createSelectorQuery();
        }else{
            query = wx.createSelectorQuery();
        }
        query.select("#"+data.id).fields({ node: true, size: true }).exec((res) => {
            const canvas = res[0].node;
            ctx = canvas.getContext('2d');
            canvas.width = 630;
            canvas.height = 830;
            let img1 = new Promise((resolve, reject)=> {
                getImageInfo(canvas, data.imgurl, resolve, reject);
            })
            let img2 = new Promise((resolve, reject)=> {
                getImageInfo(canvas, data.qrcode, resolve, reject);
            })
            Promise.all([img1, img2]).then(function (res) {
                // 首图
                ctx.drawImage(res[0], 0, 0, canvas.width, canvas.height);
                // 二维码
                ctx.drawImage(res[1], 202, 498, 208, 208);
                wx.canvasToTempFilePath({
                    canvas: canvas,
                    width: canvas.width,
                    height: canvas.height,
                    success:(res)=> {
                        cbResolve(res.tempFilePath);
                    },
                    fail:(res)=> {
                        cbReject(0);
                        Log.error(JSON.stringify(res));
                    },
                })
            }).catch((res)=>{
                Log.error(JSON.stringify(res));
                cbReject(0);
            });

        })
    });
}
